import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import renderModal, { getModelValue, initModelValue, renderForm, type FormModalDto } from '@/components/modal/Modal'
import { recharge, updatePayManagerUser } from '@/api/pay'
import type { FilterDto } from '@/render/FilterRender'
import {
    getKeyToEnum,
    PayModeCnEnum,
    PayModeEnum,
    SaleSceneGiftCnEnum,
    SaleSceneCnEnum,
    SaleSceneGiftEnum,
    SaleSceneEnum
} from '@/const/enum'

import type { CompanyDetailDto } from '@/api/company/types'
import { getCompanyDetail } from '@/api/company'
import { confirm, getReceiptData, goBack } from '@/utils/util'
import { Button, Image, message, Tag } from 'ant-design-vue'
import dayjs from 'dayjs'
import CustomTitle from '@/components/custom-title/Index'
import { createVNode } from 'vue'
import type { OptionDto } from '@/components/low-code/types'
import SuccessComponent from '../../open-products/components/SuccessComponent'
// import { SuccessComponent } from './SuccessComponent'

@Component({
    expose: ['getData']
})
export class Paywage extends Render {

    @Prop() companyDetail!: CompanyDetailDto

    companyId = null as null | number

    showRecharge = false

    isSuccess = false

    successHint = ''

    @Emit('refresh')
    handleRefresh() {}

    @Watch('companyDetail')
    async handleWatchCompanyDetail() {
        if (this.companyDetail.channelId) {
            this.rechargeFormConfig.items.receiptId.options = await getReceiptData(
                this.companyDetail.channelId
            )
        }
    }

    // 充值弹框
    rechargeFormConfig = this.initRechargeFormConfig() as FormModalDto
    initRechargeFormConfig() {
        return {
            title: '',
            width: '600px',
            theme: 'light',
            show: false,
            items: {
                payMode: {
                    name: '付款方式',
                    element: 'radioGroup',
                    options: getKeyToEnum(PayModeCnEnum, false, ['公对公', '私对公', '赠送']),
                    required: true,
                    callback: {
                        change: (val: number) => {
                            const items = this.rechargeFormConfig.items
                            this.initFormItem()
                            items.salesScenario.value = ''
                            items.salesScenario.options =
                                val === PayModeEnum.GIFT
                                    ? getKeyToEnum(SaleSceneGiftCnEnum)
                                    : getKeyToEnum(SaleSceneCnEnum)
                        }
                    }
                },
                salesScenario: {
                    name: '销售场景',
                    element: 'select',
                    required: true,
                    options: getKeyToEnum(SaleSceneCnEnum),
                    span: 12,
                    callback: {
                        change: (val: number) => {
                            this.initFormItem()
                        }
                    }
                },
                payMoney: {
                    name: '服务金额',
                    element: 'inputNumber',
                    required: true,
                    defaultValue: 0,
                    span: 12,
                    params: {
                        min: 0
                    }
                },
                giftAccountTime: {
                    name: '赠送时间',
                    element: 'input',
                    required: true,
                    span: 12,
                    params: {
                        suffix: '天'
                    },
                    hidden: true,
                    callback: {
                        input: (ev: InputEvent) => {
                            this.setAccountAndSeatExpireTime(ev, 'day')
                        }
                    }
                },
                hint: {
                    name: '',
                    element: 'text',
                    span: 12,
                    params: {
                        prefix: <></>
                    },
                    hidden: true
                },
                rechargeAmount: {
                    name: '购买月份',
                    element: 'select',
                    span: 12,
                    required: true,
                    options: this.createMonthOption(),
                    callback: {
                        change: (val: number) => {
                            this.setAccountAndSeatExpireTime(val, 'month')
                        }
                    }
                },
                buySeatCount: {
                    name: '另购席位',
                    element: 'inputNumber',
                    required: true,
                    defaultValue: 1,
                    span: 12,
                    params: {
                        min: 1
                    },
                    hidden: true
                },
                accountExpireTime: {
                    name: '产品过期时间',
                    element: 'datetime',
                    required: true,
                    span: 12,
                    labelCol: {
                        style: {
                            width: '8em'
                        }
                    },
                    hidden: true
                },
                seatExpireTime: {
                    name: '席位过期时间',
                    element: 'datetime',
                    required: true,
                    labelCol: {
                        style: {
                            width: '8em'
                        }
                    },
                    span: 12,
                    hidden: true
                },
                receiptId: {
                    name: '收款账户',
                    element: 'select',
                    optionsType: '',
                    required: true,
                    span: 12,
                },
                voucherUrl: {
                    name: '上传凭证',
                    element: 'upload',
                    type: 'text',
                    params: {
                        autoUpload: false,
                        accept: '.png,.jpg,.jpeg',
                        hint: '大小限制5MB，支持png、jpeg、jpg格式文件'
                    }
                },
                remark: {
                    name: '备注',
                    element: 'textarea',
                    params: { rows: 4 }
                }
            },
            complete: async () => {
            },
            cancel: () => {
            },
            init: () => {
                initModelValue(this.rechargeFormConfig)
            }
        } as FormModalDto
    }
    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    filterBtnConfig() {
        return {} as FilterDto
    }

    createMonthOption() {
        const arr = [] as OptionDto[]
        for (let i = 1; i <= 12; i++) {
            arr.push({ label: `${i}月`, value: i })
        }
        return arr
    }

    initFormItem() {
        const formData = getModelValue(this.rechargeFormConfig)
        const items = this.rechargeFormConfig.items

        const hasSeat =
            formData.salesScenario === SaleSceneGiftEnum.PRODUCT_AND_SEAT ||
            formData.salesScenario === SaleSceneGiftEnum.SEAT ||
            formData.salesScenario === SaleSceneEnum.EXTEND_AND_SEAT ||
            formData.salesScenario === SaleSceneEnum.FITST_AND_SEAT ||
            formData.salesScenario === SaleSceneEnum.SEAT
        const hasProcuct =
            formData.salesScenario === SaleSceneGiftEnum.PRODUCT_AND_SEAT ||
            formData.salesScenario === SaleSceneGiftEnum.PRODUCT ||
            formData.salesScenario === SaleSceneEnum.FIRST_SIGN ||
            formData.salesScenario === SaleSceneEnum.EXTEND_SIGN ||
            formData.salesScenario === SaleSceneGiftEnum.PRODUCT ||
            formData.salesScenario === SaleSceneEnum.FITST_AND_SEAT ||
            formData.salesScenario === SaleSceneEnum.EXTEND_AND_SEAT

        items.giftAccountTime.hidden = formData.payMode !== PayModeEnum.GIFT

        items.payMoney.hidden = formData.payMode === PayModeEnum.GIFT
        items.rechargeAmount.hidden = formData.payMode === PayModeEnum.GIFT
        items.voucherUrl.hidden = formData.payMode === PayModeEnum.GIFT

        items.buySeatCount.name = formData.payMode === PayModeEnum.GIFT ? '赠送席位' : '另购席位'
        items.buySeatCount.hidden = !hasSeat
        items.accountExpireTime.hidden = !hasProcuct
        items.seatExpireTime.hidden = !hasSeat
    }

    /**
     * 根据购买月份设置席位过期时间，若产品本身没有过期，就从过期时间起计算，过产品过期了，就从当前时间起开始计算
     */
    setAccountAndSeatExpireTime(month: number | InputEvent, type: 'month' | 'day') {
        const expireTime = this.companyDetail.accountExpireTime
            ? new Date(this.companyDetail.accountExpireTime).getTime()
            : 0
        const nowTime = new Date().getTime()
        const formData = getModelValue(this.rechargeFormConfig)
        const setDate = expireTime > nowTime ? this.companyDetail.accountExpireTime : new Date()

        formData.accountExpireTime = dayjs(setDate)
            .add(month as number, type)
            .toISOString()
        formData.seatExpireTime = dayjs(new Date())
            .add(month as number, type)
            .toISOString()
        initModelValue(this.rechargeFormConfig, formData)
    }

    async onSubmit() {
        const data = getModelValue(this.rechargeFormConfig)

        await confirm(
            createVNode('span', null, [
                '充值动作不可逆，本次充值',
                createVNode(
                    'strong',
                    {
                        style: {
                            color: 'red'
                        }
                    },
                    data.payMoney
                ),
                '元，确认充值？'
            ])
        )

        delete data.hint
        delete data.giftAccountTime
        data.companyId = this.companyDetail.companyId
        data.openAccountMoney = 0

        if (data.voucherUrl?.length && Array.isArray(data.voucherUrl)) {

            data.voucherUrl = data.voucherUrl[0].base64
        }

        await recharge(data)
        message.success('充值成功')
        this.successHint = `已成功为「${this.companyDetail.companyName}」充值了发薪账户，可在「充值审批」中查看结果`
        this.isSuccess = true

    }

    created() {
        this.basicForm = renderForm(this.rechargeFormConfig)
        // if (this.$route.query.companyId) {
        //     this.companyId = Number(this.$route.query.companyId)
        //     this.initData()
        // }
    }

    renderStatistics() {
        return <></>
    }

    renderRightBtns() {
        return <></>
    }

    render() {
        return (
            this.isSuccess ? <div class="flex h-full justify-center items-center"><SuccessComponent text="充值成功" hint={this.successHint} /></div>  : 
                <div class="flex flex-col gap-20px h-full">
                    <div class="flex-1">
                        <CustomTitle>续费发薪专户</CustomTitle>
                        <div class="mt-20px">{this.basicForm.element()}</div>
                    </div>
                    <div class="pt-19px flex justify-center gap-20px">
                        <Button onClick={goBack}>取消</Button>
                        <Button type="primary" onClick={this.onSubmit}>确认</Button>
                    </div>
                </div>
        )
    }
}

export default toNative<
    { companyDetail: CompanyDetailDto },
    { refresh: () => void }
        >(Paywage)
